package com.jtpay.textpay.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jtpay.textpay.AppidDataProvider;
import com.jtpay.textpay.BuildConfig;
import com.jtpay.textpay.R;
import com.jtpay.textpay.util.SharedPreferenceUtil;

import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import static com.jtpay.textpay.TextApplication.getSharedPreferenceUtil;
import static sdk.pay.constant.PayExternalConstant.ACTION_PAY_CALLBACK;
import static sdk.pay.constant.PayExternalConstant.PAY_STATUS;
import static sdk.pay.listener.PayGetPayStatusListener.FAILURE;
import static sdk.pay.listener.PayGetPayStatusListener.SUCCESS;

public class TextActivity extends AppCompatActivity {
    private LinearLayout mLayout;
    private TextView mProductPrice, mProductName;
    private Toast mToast;
    private String mDemoMoney = "10.00";
    private PayCallbackReceiver mReceiver;
    private EditText tvAppid;
    private EditText tvAppKey;
    private EditText tvAesKey;
    private EditText tvAesV;
    public static String APP_ID;
    public static String APP_KEY;
    public static String KEY;
    public static String VECTOR;
    private SharedPreferenceUtil sharedPreferenceUtil = getSharedPreferenceUtil();
    private String id = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text);
        initViews();
        initData();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mReceiver = new PayCallbackReceiver();
        IntentFilter intentFilter = new IntentFilter(ACTION_PAY_CALLBACK);
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private void initViews() {
        mLayout = findViewById(R.id.layout);
        mProductPrice = findViewById(R.id.product_price);
        mProductName = findViewById(R.id.product_name);
        tvAppid = findViewById(R.id.appid);
        tvAppKey = findViewById(R.id.appKey);
        tvAesKey = findViewById(R.id.aesKey);
        tvAesV = findViewById(R.id.aesV);
//        tvAppid.setText(BuildConfig.APPID);
//        tvAppKey.setText(BuildConfig.APP_KEY);
//        tvAesKey.setText(BuildConfig.KEY);
//        tvAesV.setText(BuildConfig.VECTOR);
    }

    @Override
    protected void onResume() {
        super.onResume();
        id = sharedPreferenceUtil.spRead(this, "appid");
        if (id != null && !id.equals("")) {
            tvAppid.setText(sharedPreferenceUtil.spRead(this, "appid"));
            tvAppKey.setText(sharedPreferenceUtil.spRead(this, "appKey"));
            tvAesKey.setText(sharedPreferenceUtil.spRead(this, "aesKey"));
            tvAesV.setText(sharedPreferenceUtil.spRead(this, "aesV"));
        }
        sharedPreferenceUtil.spRemove(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    private void initData() {

        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        mLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                APP_ID = tvAppid.getText().toString();
                APP_KEY = tvAppKey.getText().toString();
                KEY = tvAesKey.getText().toString();
                VECTOR = tvAesV.getText().toString();
                PayActivity.startActivity(TextActivity.this
                        , mProductName.getText().toString()
                        , mProductPrice.getText().toString()
                        , APP_ID, APP_KEY, KEY, VECTOR);
            }
        });
        mLayout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showInputDialog(mProductPrice);
                return true;
            }
        });
        mProductPrice.setText(mDemoMoney);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_tools:
                if (AppidDataProvider.isDbNull(TextActivity.this)) {
                    showToast("数据库为空");
                } else {
                    Intent intent = new Intent(TextActivity.this, AppidListActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.clean:
                tvAppid.getEditableText().clear();
                tvAppKey.getEditableText().clear();
                tvAesKey.getEditableText().clear();
                tvAesV.getEditableText().clear();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showInputDialog(final TextView textView) {
        /*@setView add EditView  */
        final EditText editText = new EditText(TextActivity.this);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        editText.setText(textView.getText().toString());
        editText.addTextChangedListener(new SearchWatcher(editText));
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(TextActivity.this);
        inputDialog.setTitle(R.string.please_input_price).setView(editText);
        inputDialog.setPositiveButton(R.string.confirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            if (!TextUtils.isEmpty(editText.getText().toString())) {
                                DecimalFormat df = new DecimalFormat("0.00");
                                mDemoMoney = df.format(Double.parseDouble(editText.getText().toString()));
                                textView.setText(mDemoMoney);
                                mProductPrice.setText(mDemoMoney);
                            } else {
                                Toast.makeText(TextActivity.this, R.string.data_cannot_empty, Toast.LENGTH_SHORT).show();
                            }
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            textView.setText(mProductPrice.getText().toString());
                            Toast.makeText(TextActivity.this, R.string.data_format_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                }).show();
    }

    private String stringFilterText(String str) throws PatternSyntaxException {
        String regEx = "[^0-9.]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }


    private class SearchWatcher implements TextWatcher {
        //Listen to changes the text box
        private EditText editText;

        SearchWatcher(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void onTextChanged(CharSequence ss, int start, int before, int count) {
            String editable = editText.getText().toString();
            String str = stringFilterText(editable);
            if (str.contains(".")) {
                String strDecimal = str.substring(str.indexOf("."));
                if (strDecimal.length() > 3) {
                    str = str.substring(0, str.indexOf(".") + 3);
                }
            }
            if (!editable.equals(str)) {
                editText.setText(str);
                //new selection position
                editText.setSelection(str.length());
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
    }

    private void showToast(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mToast.setText(str);
                mToast.show();
            }
        });
    }

    private class PayCallbackReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_PAY_CALLBACK.equals(intent.getAction())) {
                int status = intent.getIntExtra(PAY_STATUS, FAILURE);
                if (status == SUCCESS) {
                    showToast(getString(R.string.pay_success));
                } else {
                    showToast(getString(R.string.pay_failure));
                }
            }
        }
    }
}
